import { FETCH_BASE_URL } from "./constant"
import PollingManager from "./PollingManager";

document.addEventListener('DOMContentLoaded', () => {
  const settingsForm = document.getElementById('settingsForm') as HTMLFormElement;
  const openKey = document.getElementById('openKey') as HTMLInputElement;
  const passwd = document.getElementById('passwd') as HTMLInputElement;
  const saveSettings = document.getElementById('saveSettings') as HTMLButtonElement;

  // 初始化检查登录状态
  checkLoginStatus();

  const handleLogoutRemoveToken = async () => {
    const storage = await chrome.storage.sync.get([
      "baoyiplus_accessToken",
    ]);
    const {
      baoyiplus_accessToken = "",
    } = storage;
    const apiurl = "https://java.baoyierp.com/api/user/logout";
    return fetch(apiurl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + baoyiplus_accessToken,
      },
    });
  }
  const handleGetActivity = async () => {
    const storage = await chrome.storage.sync.get([
      "baoyiplus_accessToken",
    ]);
    const {
      baoyiplus_accessToken = "",
    } = storage;
    const apiurl = "https://java.baoyierp.com/api/user/commonLogin/getActivity";
    return fetch(apiurl, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + baoyiplus_accessToken,
      },
    });
  };
  const polling = new PollingManager(60 * 1000 * 10, handleGetActivity);

  settingsForm.addEventListener('submit', async function(e) {
    e.preventDefault();
    await handleLogin();
  });

  // 检查登录状态函数
  async function checkLoginStatus() {
    
    const storage = await chrome.storage.sync.get([
      'baoyiplus_accessToken',
      'baoyiplus_expiresIn',
      'baoyiplus_username'
    ]);
      // 解构赋值，设置默认值防止undefined
  const { 
    baoyiplus_accessToken = '', 
    baoyiplus_expiresIn = 0,
    baoyiplus_username = ''
  } = storage;


    if (baoyiplus_accessToken) {
      const isExpired = checkTokenExpired(baoyiplus_expiresIn);
      if (!isExpired) {
        saveSettings.innerHTML = '登录成功';
        saveSettings.disabled = true;
        // 用户名输入框设置
      openKey.disabled = true;
      openKey.value = baoyiplus_username || '已登录用户';

      openKey.style.backgroundColor = '#f0f0f0'; // 视觉区分
      
        // 密码框设置
      passwd.disabled = true;
      passwd.value = '********'; // 掩码显示
      passwd.style.backgroundColor = '#f0f0f0';
      polling.start(); // 启动轮询
       // 可选：添加"退出登录"按钮
       if (!document.getElementById('logoutBtn')) {
        const logoutBtn = document.createElement('button');
        logoutBtn.id = 'logoutBtn';
        logoutBtn.textContent = '退出登录';
        logoutBtn.style.marginLeft = '10px';
        logoutBtn.onclick = async () => {
          await handleLogoutRemoveToken();
          await clearLoginData();
          polling.stop(); // 停止轮询
          location.reload(); // 刷新页面恢复登录表单
        };
        settingsForm.appendChild(logoutBtn);
      }
        
      } else {
        await clearLoginData();
        saveSettings.innerHTML = '登录已过期，请重新登录';
      }
    }
  }

  // 检查token是否过期（针对时间戳格式）
  function checkTokenExpired(expiresIn: string | number): boolean {
    if (!expiresIn) return true;
    
    // 统一转换为数字
    const expiryTime = typeof expiresIn === 'string' 
      ? parseInt(expiresIn) 
      : expiresIn;
    
    // 获取当前时间戳（毫秒）
    const currentTime = new Date().getTime();
    return currentTime > expiryTime;
  }

  // 清除登录数据
  async function clearLoginData() {
    await chrome.storage.sync.remove([
      'baoyiplus_accessToken',
      'baoyiplus_expiresIn'
    ]);
  }

  // 处理登录逻辑
  async function handleLogin() {
    saveSettings.disabled = true;
    saveSettings.innerHTML = '登录中...';

    try {
      const result = await login(openKey, passwd);

      if (result?.code === 0 && result.data) {
        await chrome.storage.sync.set({
          'baoyiplus_accessToken': result.data.accessToken,
          'baoyiplus_expiresIn': result.data.expiresIn, // 存储原始时间戳
          'baoyiplus_username':openKey.value
        });
        showLoginSuccess();
      } else {
        showLoginError(result?.msg || '登录失败');
        alert(result?.msg || '登录失败');
      }
    } catch (error) {
      console.error('登录异常:', error);
      showLoginError('网络异常');
      alert(`登录异常:${error}`);
    }
  }

  // 显示登录成功状态
  function showLoginSuccess() {
    saveSettings.innerHTML = '登录成功';
    saveSettings.disabled = true;
    location.reload(); 
  }

  // 显示登录错误状态
  function showLoginError(message: string) {
    saveSettings.innerHTML = message;
    saveSettings.style.color = 'red';
    saveSettings.disabled = false;
    
    setTimeout(() => {
      saveSettings.innerHTML = '点击登录';
      saveSettings.style.color = '';
    }, 2000);
  }

  // 登录API
  async function login(user: HTMLInputElement, passwd: HTMLInputElement) {
    const apiurl = `${FETCH_BASE_URL}/user/login`;
    //http://192.168.1.13:5201/api/user/login
    //https://java.baoyierp.com/api/user/login
    const response = await fetch(apiurl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        username: user.value,
        password: passwd.value,
        loginEntrance: 'DESKTOP_PLUGIN'
      })
    });
    return response.json();
  }
});